package com.yunwushanhe.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunwushanhe.student.bean.BizException;
import com.yunwushanhe.student.bean.ret.Result;
import com.yunwushanhe.student.bean.req.StudentAddReq;
import com.yunwushanhe.student.bean.req.PageReq;
import com.yunwushanhe.student.bean.req.StudentUpdateReq;
import com.yunwushanhe.student.entity.Student;
import com.yunwushanhe.student.mapper.StudentMapper;
import com.yunwushanhe.student.service.StudentService;
import com.yunwushanhe.student.util.PageHelperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(StudentAddReq addStudentInfo) {
        LambdaQueryWrapper<Student> qw = new LambdaQueryWrapper<>();
        qw.eq(Student::getNo,addStudentInfo.getNo());
        Long count = studentMapper.selectCount(qw);
        log.info("添加学生时根据学号（no）检测到已有的数量{}",count);
        if(count > 0){
            throw new BizException("学号已存在！"); // 一旦出现异常，这个函数后面的程序就不会运行了
        }
        Student student = new Student();
        BeanUtils.copyProperties(addStudentInfo,student);
        studentMapper.insert(student);
    }

    @Override
    public Result<List<Student>> selectPage(PageReq pageReq) {
        PageHelperUtil.startPage(pageReq.getPageNow(),pageReq.getPageSize());
        List<Student> list = studentMapper.queryList(pageReq);
        return PageHelperUtil.wrapPageData(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> deleteById(Long id) {
        studentMapper.deleteById(id);
        return Result.ok("删除成功");
    }

    @Override
    public Result<Student> selectById(Long id) {
        Student student = studentMapper.selectById(id);
        // 这个方法如果查出来为空，应该单独处理一下
        return Result.ok(student);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateById(StudentUpdateReq updateReq) {
        Student student = new Student();
        BeanUtils.copyProperties(updateReq,student);
        studentMapper.updateById(student);
        return Result.ok("更新成功！");
    }

    @Override
    public Result<List<Student>> selectAll() {
        List<Student> list = studentMapper.queryList(new PageReq());
        return Result.ok(list);
    }
}
